package 系统复习.链表;

class ListNode {
    int val;
    ListNode prev, next;
    ListNode() {}
    ListNode(int val) {
        this.val = val;
    }
}

public class L707_双 {

    int size;
    ListNode head, tail;

    public L707_双() {
        size = 0;
        head = new ListNode();
        tail = new ListNode();
        head.next = tail;
        tail.prev = head;
    }

    public int get(int index) {

        if (index < 0 || index>= size) return  -1;
        ListNode cur = head;
        if (index >= size / 2) {
            cur = tail;
            for (int i = 0; i < size - index; i++) {
                cur = cur.prev;
            }
        } else {
            for (int i = 0; i <= index; i++) {
                cur = cur.next;
            }
        }
        return cur.val;
    }

    public void addAtHead(int val) {
        addAtIndex(0, val);
    }

    public void addAtTail(int val) {
        addAtIndex(size, val);
    }

    public void addAtIndex(int index, int val) {
        if (index > size) return;
        if (index < 0) index = 0;
        size++;
        ListNode pre = head;
        for (int i = 0; i < index; i++) {
            pre = pre.next;
        }
        ListNode listNode = new ListNode(val);
        listNode.next = pre.next;
        pre.next.prev = listNode;
        listNode.prev = pre;
        pre.next = listNode;

    }

    public void deleteAtIndex(int index) {
        if (index < 0 || index >= size) return;
        size--;
        ListNode pre = head;
        for (int i = 0; i < index; i++) {
            pre = pre.next;
        }
        pre.next.next.prev = pre;
        pre.next = pre.next.next;
    }

}
